package com.lianniu.web.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class WeiXinDownloadUtil {

	//private static String urlPath = "/home/firmboy/weixin-tomcat/webapps/weixin/img/";测试

	private static String urlPath = "/mnt/tomcat/weixin/webapps/ROOT/img/";


	// private static String urlPath = "D://";

	//private static String imgPath = "http://47.95.11.244/weixin/img/";测试
	private static String imgPath = "http://www.nashannacha.com:8081/img/";

	public static void main(String[] args) {
		String[] mediaIds = new String[] { "4Fi7M_6qqzvxhbkBZbDlS1z-uI0-mIBIU_bQrzspLbd41BHrJrAUbj6TdgiUR80W",
				"I7mySjXuiB57KyDdmApmaObO0u06f63uVI9pMFpIplhcbsnn__cbqyJMO-KJ86C7" };
		for (String mediaId : mediaIds) {
			String accessToken = "EtVi12-immszc0qdN8OPs86CXRAXMfz3XZ-yYQQ5GQChLZ0SoZnQaWJK35pUl0ytMvcTbFJvBXhVWVvgKsOQbjREFNKZ9cxFvGXAs5IUAcWH8HnpR5P2hUFNh4smdKXRNDNiAGAVLV";
			String downloadMedia = downloadMedia(mediaId, accessToken, "img//img//");
			System.err.println(downloadMedia);
		}
	}

	/**
	 * 获取媒体文件
	 * 
	 * @param accessToken
	 *            接口访问凭证
	 * @param media_id
	 *            媒体文件id
	 * @param path
	 *            具体文件夹路径
	 */
	public static String downloadMedia(String mediaId, String accessToken, String path) {
		String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		System.err.println("requestUrl:"+requestUrl);
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
		System.err.println("开始下载mediaId:" + mediaId);
		HttpURLConnection conn = null;
		System.err.println("开始时间：" + System.currentTimeMillis());
		try {
			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = bis.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			byte[] filebyte = swapStream.toByteArray();
			String imgShowPath = store(filebyte, path);
			System.err.println("下载图片结束：mediaId:" + mediaId + "-imgShowPath:" + imgShowPath);
			System.err.println("结束时间：" + System.currentTimeMillis());
			return imgShowPath;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		return "";
	}

	public static String store(byte[] data, String path) {
		String name = UUID.randomUUID().toString().replaceAll("-", "");
		File file = new File(urlPath + path);
		if (!file.exists()) {
			file.mkdirs();
		}
		String imgFilePath = urlPath + path + name + ".jpg";// 新生成的图片
		System.err.println("生成图片路径：" + imgFilePath);
		String imgShowPath = imgPath + path + name + ".jpg";// 生成图片的显示路径
		try {
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(data);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return imgShowPath;
	}
}
